import os
import re

from WebBackend.utils import mylog
from WebBackend.utils.executeCMD import execute_cmd
from WebBackend.utils.readFile import read_file_sync
import App_setting as setting


def read_configuration_file(*, file_path: str = '', return_type: str | list[str] = None):
    config_dict: dict = {}
    commented_config_dict: dict = {}
    text_lines: list[str] = []
    commented_text_lines: list[str] = []
    text = read_file_sync(file_path, 'list')
    for line in text:
        line = line.strip()
        if not line:  # 跳过注释和空行
            continue
        if '=' in line:  # 确保是 key=value 格式
            key, value = line.split('=', 1)  # 按第一个 `=` 分割
            if line.startswith('#'):
                commented_config_dict[key.strip()] = value.strip().lstrip('#')
                commented_text_lines.append(line)
            else:
                config_dict[key.strip()] = value.strip()
                text_lines.append(line)
    if type(return_type) == str:
        if return_type == 'config_dict':
            return config_dict
        elif return_type == 'commented_config_dict':
            return commented_config_dict
        elif return_type == 'text_lines':
            return text_lines
        elif return_type == 'commented_text_lines':
            return commented_text_lines
    elif type(return_type) == list:
        result_set = []
        data_set = {
            'config_dict': config_dict,
            'commented_config_dict': commented_config_dict,
            'text_lines': text_lines,
            'commented_text_lines': commented_text_lines
        }
        for k in return_type:
            result_set.append(data_set[k])
        return result_set
    else:
        return text_lines


def configuration_liner_comparator(old_lines, new_lines, return_type: str | list[str] = None) -> list:
    """return_type available key: created, removed, common"""
    set1 = set(old_lines)
    set2 = set(new_lines)
    ############################
    # ORIGINAL = ["苹果", "香蕉", "橙子", "葡萄"]
    # 删除一个 "橙子" =  ["苹果", "香蕉",  "葡萄"]
    # 增加一个 "西瓜" = ["苹果", "香蕉",  "葡萄", "西瓜"]
    # 删除一个 "苹果" =  ["香蕉",  "葡萄"]
    # NEW = ["香蕉",  "葡萄", "西瓜"]
    ############################
    # set1 比 set2 多的项目（删除的）
    only_in_set1 = list(set1.difference(set2))
    # set2 比 set1 多的项目（新增的）
    only_in_set2 = list(set2.difference(set1))
    # 相同项目
    common = list(set1.intersection(set2))
    if type(return_type) == str:
        if return_type == 'created' or return_type == 'only_in_line1':
            return only_in_set2
        elif return_type == 'removed' or return_type == 'only_in_line2':
            return only_in_set1
        else:
            return common
    elif type(return_type) == list:
        result_set = []
        data_set = {
            'created': only_in_set2,
            'removed': only_in_set1,
            'common': common,
        }
        for k in return_type:
            result_set.append(data_set[k])
        return result_set
    else:
        return common


def clean_comment(file: str):
    try:
        # 2. 读取原始文件并处理内容
        with open(file, 'r') as f:
            lines = f.readlines()

        # 3. 过滤掉注释行和被注释的配置项
        cleaned_lines = []
        for line in lines:
            # 去除行首尾空白字符
            stripped_line = line.strip()
            # 保留非空行且不是注释的行（不以#开头）
            if stripped_line and not stripped_line.startswith('#'):
                cleaned_lines.append(line)

        # 4. 将处理后的内容写回原始文件
        with open(file, 'w') as f:
            f.writelines(cleaned_lines)

        return True, "操作成功完成"

    except FileNotFoundError:
        return False, "错误：未找到/etc/vsftpd.conf文件"
    except PermissionError:
        return False, "错误：没有足够的权限操作该文件"
    except Exception as e:
        return False, f"发生未知错误：{str(e)}"


def get_configuration_file_path() -> str:
    true_file_path: str = ''
    if setting.path.file_vsftpd_conf:
        if os.path.isfile(setting.path.file_vsftpd_conf):
            true_file_path = setting.path.file_vsftpd_conf
        else:
            mylog.error('[#b38b]配置文件错误：[App_setting.py> path > file_vsftpd_conf] 定义的文件不存在')
            exit(-1)
    else:
        text = execute_cmd('systemctl status vsftpd', 'list')
        if not text:
            mylog.error('[#1c8f]系统服务读取错误：找不到配置文件位置（Loaded: loaded (*)）')
            exit(-1)
        for line in text:
            if line.find('Loaded: '):
                if match := re.search(r'(/\S+?\.service)', line):
                    # 使用捕获组提取文件路径，注意去除括号
                    true_file_path = match.group(1)
                    break
                else:
                    continue
            else:
                continue
    if true_file_path != setting.path.file_vsftpd_conf:
        mylog.warn("[App_setting.py]>path.file_vsftpd_conf配置异常: 文件位置与系统服务定义位置不一致")
    ###################################################
    return true_file_path
